package myStack;

import java.util.Arrays;

public class myStack<T> implements IStack<T>{

    private T[] elem;
    private int usedSize;
    private static final int DEFAULT_CAPACITY = 10;

    public myStack() {
        elem = (T[]) new Object[DEFAULT_CAPACITY];
    }

    @Override
    public void push(T x) {
        if(full())
        {
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = x;
        usedSize++;
    }

    private void PopException() throws myStackException
    {
        throw new myStackException("pop失败, 栈为空");
    }
    @Override
    public T pop() {
        if(empty())
        {
            PopException();
        }
        T old = elem[usedSize - 1];
        usedSize--;
        return old;
    }

    private void PeekException() throws myStackException{
        throw new myStackException("peek失败, 栈为空!");
    }
    @Override
    public T peek() {
        if(empty())
        {
            PeekException();
        }

        return elem[usedSize - 1];
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public boolean empty() {
        return this.usedSize == 0;
    }

    @Override
    public boolean full() {
        return elem.length == this.usedSize;
    }
}
